package com.woc.boot.admin.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import freemarker.template.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * 登录拦截器
 *
 * @author woc
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    
    @Autowired
    private Configuration configuration;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
    }

    private void loginHandle(HttpServletRequest request, HttpServletResponse response) throws Exception {
        boolean isAjax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
        if (isAjax) {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.write("未登录或登录失效，请重新<a href=\"/auth/login\">登录</a>！");
                writer.flush();
            } catch (Exception e) {
                logger.error("LoginInterceptor loginHandle error:", e);
            } finally {
                if (writer != null) {
                    writer.close();
                }
            }
        } else {
            String loginUrl = "/auth/login?refer=" + request.getRequestURI();
            response.sendRedirect(loginUrl);
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //验证是否登录
        HttpSession session = request.getSession();
        if (session == null) {
            logger.warn("LoginInterceptor preHandle session empty");
            loginHandle(request, response);
            return false;
        }
        String userName = (String) session.getAttribute("userName");
        if (userName == null) {
            logger.warn("LoginInterceptor preHandle userName empty: sessionId={}", session.getId());
            loginHandle(request, response);
            return false;
        }
        configuration.setSharedVariable("userName", userName);
        String userPerm = (String) session.getAttribute("userPerm");
        configuration.setSharedVariable("userPerm", userPerm);
        return true;
    }
}

